package com.itheima.health.service.impl;

import com.itheima.health.dto.MobileCodeDTO;
import com.itheima.health.service.MobileValidateCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class MobileValidateCodeServiceImpl implements MobileValidateCodeService {
    @Autowired
    private StringRedisTemplate srt;

    /**
     * 发送验证码
     * @param type
     * @param telephone
     * @return
     */
    @Override
    public String send(String type, String telephone) {
        return genCode(type, telephone);
    }

    /**
     * 验证码登录校验
     * @param dto
     * @return
     */
    @Override
    public Boolean veriyf(MobileCodeDTO dto) {
        HashOperations<String, Object, Object> opsForHash = srt.opsForHash();
        Object redisCode = opsForHash.get(dto.getTelephone(), dto.getType());

        return String.valueOf(redisCode).equals(dto.getValidateCode());
    }

    private String genCode(String type, String telephone) {

        HashOperations<String, Object, Object> opsForHash = srt.opsForHash();
        Random random = new Random();

        String str = "1234567890";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            sb.append(str.charAt(random.nextInt(10)));
        }
        String code = sb.toString();
        //放入redis
        opsForHash.put(telephone, type, sb.toString());
        //设置过期时间
        srt.expire(telephone, 2L, TimeUnit.MINUTES);

        System.out.println(telephone + "的" + type + "验证码: " + code);
        return code;
    }
}
